package com.paper.tiger.easy.rpc.s.client.server;

import com.paper.tiger.easy.rpc.s.client.client.ContextManager;
import com.paper.tiger.easy.rpc.s.client.common.Dove;
import com.paper.tiger.easy.rpc.s.client.common.LetterType;
import com.paper.tiger.easy.rpc.s.client.execute.FlyDove;
import com.paper.tiger.easy.rpc.s.client.registy.common.RegisterConfig;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 */
public class InvokeServiceHandler extends SimpleChannelInboundHandler<Dove>
{

    /**
     * 执行具体业务的线程池
     */
    private static final ThreadPoolExecutor executor =
            new ThreadPoolExecutor(1,2,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000)
            ,new ThreadPoolExecutor.AbortPolicy());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Dove msg) throws Exception
    {
        LetterType type = LetterType.getByCode(msg.getLetterType());
        FlyDove flyDove = (FlyDove) RegisterConfig.get(type.getRegisterName());
        executor.execute(()->flyDove.service(msg,ctx));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        ctx.close();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception
    {
        ContextManager.getInstance().removeServerChannel();
    }
}
